#pragma once

#include <QObject>
#include <QHash>
#include <QList>
#include <QString>
#include <QTcpSocket>
#include <memory>
#include "third_block_area.h"
#include "infrastructure/io/http_server.h"
#include "kernel/interfaces/ILogger.h"

namespace application {
namespace lift { class LiftManager; }
namespace third_area {

/**
 * @brief 第三方区域管理器
 * @details 管理所有第三方阻塞区域，处理HTTP请求
 */
class ThirdAreaManager : public QObject {
    Q_OBJECT

public:
    explicit ThirdAreaManager(std::shared_ptr<kernel::ILogger> logger = nullptr,
                             QObject* parent = nullptr);
    ~ThirdAreaManager() = default;

    /**
     * @brief 初始化HTTP服务器
     * @param port 监听端口，默认9001
     */
    bool initConnection(quint16 port = 9001);

    /**
     * @brief 绑定共享电梯管理器
     */
    void setLiftManager(std::weak_ptr<lift::LiftManager> liftManager);

    /**
     * @brief 添加区域
     */
    void addArea(const QString& areaId, int floor, int liftNum = 0);

    /**
     * @brief 移除区域
     */
    void removeArea(const QString& areaId);

    /**
     * @brief 关联区域到管理器
     */
    void connectArea(const QString& areaId, ThirdBlockArea* area);

    /**
     * @brief 获取区域
     */
    ThirdBlockArea* getArea(const QString& areaId) const;

    /**
     * @brief 获取所有区域
     */
    QList<ThirdBlockArea*> getAllAreas() const { return m_areaList; }

signals:
    void areaOccupied(QString areaId, QString vehicleId);
    void areaReleased(QString areaId, QString vehicleId);

private:
    /**
     * @brief 解析HTTP POST请求字符串
     * @param srcString 原始字符串
     * @param res 资源名称(区域ID)
     * @param action 动作(hold/release)
     * @param rid 请求ID(车辆ID)
     * @return true表示解析成功
     */
    bool parseRequestString(const QString& srcString, QString& res, QString& action, QString& rid);

    /**
     * @brief 处理POST数据
     */
    void processPostData(QTcpSocket* socket, QString postData);

private:
    infrastructure::io::HttpServer* m_server = nullptr;
    QList<ThirdBlockArea*> m_areaList;
    QHash<QString, ThirdBlockArea*> m_areaHash;
    QHash<QString, int> m_areaLiftBindings;
    std::weak_ptr<lift::LiftManager> m_liftManager;
    std::shared_ptr<kernel::ILogger> m_logger;
};

} // namespace third_area
} // namespace application
